package com.csylh.service.impl;

import com.csylh.dao.OrderDetailMapper;
import com.csylh.dao.OrderMasterMapper;
import com.csylh.dao.WasteInfoMapper;
import com.csylh.dto.OrderDTO;
import com.csylh.entity.OrderDetail;
import com.csylh.entity.OrderMaster;
import com.csylh.entity.WasteInfo;
import com.csylh.enums.OrderStatus;
import com.csylh.enums.PayStatus;
import com.csylh.enums.ResultEnum;
import com.csylh.exception.DBException;
import com.csylh.exception.OrderException;
import com.csylh.service.OrderService;
import com.csylh.util.KeyUtil;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 留歌
 * Date: 2018/3/13 0:14
 * Description:
 */
@Service("orderService")
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private WasteInfoMapper wasteInfoMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMasterMapper orderMasterMapper;

    @Autowired
    private FileService fileService;

    /**
     * 订单详情表和订单总表入库
     * @param orderDTO
     * @return 返回订单ID
     */
    @Override
    @Transactional
    public String create(OrderDTO orderDTO) {
        BigDecimal orderAmount = new BigDecimal(0);
        String orderId = KeyUtil.genKey();
        for(OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            WasteInfo wasteInfo = wasteInfoMapper.selectWasteById(orderDetail.getWasteId());
            if(wasteInfo == null){
                log.info("【查找数据库】该废品信息不存在,wasteInfo={}",wasteInfo);
                throw new OrderException(ResultEnum.WASTE_NOT_EXIST);
            }
            //计算订单总金额
            orderAmount = wasteInfo.getWastePrice().
                    multiply(orderDetail.getWasteQuantity())
                    .add(orderAmount);
            //订单详情表入库
            BeanUtils.copyProperties(wasteInfo,orderDetail);
            orderDetail.setDetailId(KeyUtil.genKey());
            orderDetail.setOrderId(orderId);
            if(orderDetailMapper.save(orderDetail)!=1){
                throw new DBException("订单详情入库失败");
            }
        }

        //订单总表入库
        OrderMaster orderMaster = new OrderMaster();
        //保存订单照片
        BeanUtils.copyProperties(orderDTO,orderMaster);
        if(orderDTO.getOrderIcon()!=null){
            List<String> imgpaths = fileService.getImgPath(orderDTO.getOrderIcon());
            //将订单照片路径信息由数组转化为字符串，用”,“分隔
            String paths = Joiner.on(",").join(imgpaths);
            orderMaster.setOrderIcon(paths);
        }else{
            orderMaster.setOrderIcon(null);
        }
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatus.NEW.getCode());
        orderMaster.setPayStatus(PayStatus.WAIT.getCode());
        if(orderMasterMapper.save(orderMaster)!=1){
            throw new DBException("订单总表入库失败");
        }
        //TODO webSocket消息推送
        return orderId;
    }


    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterMapper.selectMasterById(orderId);
        if (orderMaster == null) {
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailMapper.selectDetailById(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new OrderException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }


    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();

        //判断订单状态
        if (orderDTO.getOrderStatus() != (OrderStatus.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatus.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        int updateResult = orderMasterMapper.cancelOrder(orderMaster);
        if (updateResult == 0) {
            log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
            throw new OrderException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }
}